﻿package com.twothreetwo.objectLoader 
{
	import com.twothreetwo.events.URLUtilsEvent;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.errors.IOError;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author 232°Studios | Neil Glenister
	 * @link www.232studios.com
	 */
	public class ObjectLoader extends MovieClip
	{
		private var loader:Loader;
		
		/**
		 * Used for loading in an Object (image, swf etc). URLUtilsEvent returns Object as a Loader
		 * @param url: the url of the object
		 * @see URLUtilsEvent to return Loader Object
		 */
		public function loadObject(url:String):void
		{
			loader = new Loader();
			var object:URLRequest = new URLRequest(url);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, objectLoaded);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			loader.addEventListener(ErrorEvent.ERROR, generalError);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
			
			try
			{
				loader.load(object);
			}
			catch (e:Error)
			{
				trace("Error loading object");
			}
		}
		
		private function objectLoaded(e:Event):void
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, objectLoaded);
			//dispatchEvent(new ObjectLoadedEvent(ObjectLoadedEvent.OBJECT_LOADED, loader, false, false));
			dispatchEvent(new URLUtilsEvent(URLUtilsEvent.OBJECT_LOADED, true));
			
			this.addChild(loader);
		}
		
		/**
		 * Load error events
		 */
		private function securityError(e:SecurityErrorEvent):void
		{
			e.target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			trace("Security error loading object: " + e.text);
		}
		
		private function generalError(e:ErrorEvent):void
		{
			e.target.removeEventListener(ErrorEvent.ERROR, generalError);
			trace("Error loading object: " + e.text);
		}
		
		private function loadError(e:IOErrorEvent):void
		{
			e.target.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
			trace("Error loading object: " + e.text);
		}
	}

}